//
//  IdentitySecondViewController.m
//  CommunityApp
//
//  Created by 秦乾龙 on 16/12/29.
//  Copyright © 2016年 秦乾龙. All rights reserved.
//

#import "IdentitySecondViewController.h"
#import "ZYButton.h"
#import "NavView.h"
#import "JKImagePickerController.h"
#import "QBImagePickerController.h"
#import "IdentityThirdViewController.h"
#import "GCQiniuUploadManager.h"
#import "WDData.h"
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kScale   ([UIScreen mainScreen].bounds.size.width)/750
@interface IdentitySecondViewController ()<UITextFieldDelegate,UITextViewDelegate,UITableViewDelegate,UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate,QBImagePickerControllerDelegate>
@property (strong,nonatomic)NSMutableArray *assetsArray;
@property (nonatomic,retain) UITableView *mainTableView;
@property (nonatomic,copy) UITextField *nameField;
@property (nonatomic,copy) UITextField *ideNumField;
@property (nonatomic,copy) UITextField *phoneNumField;
@property (nonatomic,copy) UITextField *codeField;
@property (nonatomic,copy) NSMutableArray *classNameArr;
@property (nonatomic,copy) NSMutableArray *stepFinishedImgArr;
@property (nonatomic,copy) NSMutableArray *stepUnFinishedImgArr;
@property (strong, nonatomic) UIImage *chooseImage;
@property (strong, nonatomic) UIImage *choose2Image;
@property (strong, nonatomic) UIImage *choose3Image;
@property (assign, nonatomic) NSInteger type;

@property (strong, nonatomic) NSMutableArray *imgurlArray;
@property (strong, nonatomic) NSMutableArray *imgidArray;

@end

@implementation IdentitySecondViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _stepFinishedImgArr = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4", nil];
    _stepUnFinishedImgArr = [NSMutableArray arrayWithObjects:@"1灰",@"2灰",@"3灰",@"4灰", nil];
    [self setUI];
}
- (void) setUI
{
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"身份认证"];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(backClick)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    UIButton *buttonNotice = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonNotice.frame = CGRectMake(0, 0, 63, 20);
    [buttonNotice setTitle:@"下一步" forState:UIControlStateNormal];
    buttonNotice.titleLabel.font = [UIFont systemFontOfSize:13];
    UIBarButtonItem *btnNoticeItem = [[UIBarButtonItem alloc]initWithCustomView:buttonNotice];
    [buttonNotice addTarget:self action:@selector(nextClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = btnNoticeItem;

    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,kScreenW , kScreenH-64) style:UITableViewStyleGrouped];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [self.view addSubview:_mainTableView];
    _classNameArr = [NSMutableArray arrayWithObjects:@"上传身份证正面",@"上传身份证反面",@"上传手持身份证头部照", nil];;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell =[[NSBundle mainBundle ]loadNibNamed:@"ZYTableViewCell" owner:nil options:nil][0];
    }
    //设置cell点击背景色不变
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (indexPath.section==0)
    {
        UIView *stateView = [[UIView alloc]init];
        stateView.frame = CGRectMake(0, 0, kScreenW, 200*kScale);
        stateView.backgroundColor = [UIColor whiteColor];
        [cell addSubview:stateView];
        NSMutableArray *lableTextArr = [NSMutableArray arrayWithObjects:@"填充信息",@"上传照片",@"选择收款方式",@"提交审核", nil];
        for (int i = 0; i<4; i++)
        {
            CGFloat errorW = 5*kScale;
            CGFloat stateBtnH = 82*kScale;
            CGFloat lineViewW = (kScreenW - 60*kScale -4*stateBtnH)/3+errorW;
            CGFloat lineViewH = 6*kScale;
            ZYButton *stateBtn = [ZYButton buttonWithType:UIButtonTypeCustom];
            
            
            stateBtn.frame = CGRectMake(30*kScale+(stateBtnH+lineViewW-errorW)*i, 30*kScale, stateBtnH, stateBtnH);
            
            if (i==1)
            {
                [stateBtn setImage:[UIImage imageNamed:_stepFinishedImgArr[i]] forState:UIControlStateNormal];
            }
            else
            {
                [stateBtn setImage:[UIImage imageNamed:_stepUnFinishedImgArr[i]] forState:UIControlStateNormal];
               
            }
            if (i!=0)
            {
                UIView *lineView = [[UIView alloc]init];
                lineView.frame = CGRectMake(30*kScale+(stateBtnH+lineViewW-errorW)*i-lineViewW+errorW/2, stateBtn.center.y, lineViewW, lineViewH);
                stateBtn.lineView = lineView;
                stateBtn.lineView.backgroundColor = ZallColorFromRGB(0x979797);
                [stateView addSubview:lineView];
                
            }
            [stateView addSubview:stateBtn];
            
            UILabel *stateLable = [[UILabel alloc]init];
            stateLable.text = lableTextArr[i];
            stateLable.frame = CGRectMake(0, 0, kScreenW, 40*kScale);
            stateLable.center = CGPointMake(stateBtn.center.x, stateBtn.center.y+stateBtnH/2+31*kScale);
            stateLable.textAlignment = NSTextAlignmentCenter;
            stateLable.font = [UIFont systemFontOfSize:13];
            [stateView addSubview:stateLable];
        }
    }
    else
    {
        UILabel *classNameLable = [[UILabel alloc]init];
        classNameLable.text = [NSString stringWithFormat:@"%@:",_classNameArr[indexPath.section-1]];
        classNameLable.font = [UIFont systemFontOfSize:15];
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:15],};
        //        classNameLable.textColor = [UIColor colorWithRed:158/255.0 green:158/255.0 blue:158/255.0 alpha:1.0f];
        CGSize textSize = [classNameLable.text boundingRectWithSize:CGSizeMake(MAXFLOAT, 100) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;;
        classNameLable.frame = CGRectMake(30*kScale, 0, textSize.width, 100*kScale);
        [cell addSubview:classNameLable];
        UIView *backView = [[UIView alloc]init];
        backView.layer.borderWidth = 3*kScale;
        backView.layer.borderColor = ZallColorFromRGB(0xc7c3c3).CGColor;
        backView.frame = CGRectMake(30*kScale, 100*kScale, kScreenW-60*kScale, 266*kScale);
        [cell addSubview: backView];
        
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:backView.bounds];
        [backView addSubview:imageV];
        imageV.hidden = YES;
    
        UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [addBtn setImage:[UIImage imageNamed:@"添加图片按钮"] forState:UIControlStateNormal];
        addBtn.frame = CGRectMake(0, 0, 76*kScale, 76*kScale);
        addBtn.center = backView.center;
        addBtn.enabled = NO;
//        [addBtn addTarget:self action:@selector(addClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:addBtn];
        
        if (indexPath.section == 1) {
            if (self.chooseImage) {
                imageV.image = self.chooseImage;
                imageV.hidden = NO;
                addBtn.hidden = YES;
            } else {
                imageV.hidden = YES;
                addBtn.hidden = NO;
            }
        } else if (indexPath.section == 2) {
            if (self.choose2Image) {
                imageV.image = self.choose2Image;
                imageV.hidden = NO;
                addBtn.hidden = YES;
            } else {
                imageV.hidden = YES;
                addBtn.hidden = NO;
            }
        } else if (indexPath.section == 3) {
            if (self.choose3Image) {
                imageV.image = self.choose3Image;
                imageV.hidden = NO;
                addBtn.hidden = YES;
            } else {
                imageV.hidden = YES;
                addBtn.hidden = NO;
            }
        }
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.type = indexPath.section;
    if (indexPath.section == 1) {
        [self addClick:nil];
    } else if (indexPath.section == 2) {
        [self addClick:nil];
    } else if (indexPath.section == 3)  {
        [self addClick:nil];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return 200*kScale;
    }
    return  396*kScale;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return  0.01;
    }
    return 20*kScale;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)uploadImages {
    if (self.chooseImage == nil || self.choose2Image == nil ||self.choose3Image == nil) {
        return;
    }
    [self.imgurlArray removeAllObjects];
    [self.imgidArray removeAllObjects];
    NSMutableArray *dataarray = [NSMutableArray new];
    [dataarray addObject:UIImageJPEGRepresentation(self.chooseImage, NORMALSIZE)];
    [dataarray addObject:UIImageJPEGRepresentation(self.choose2Image, NORMALSIZE)];
    [dataarray addObject:UIImageJPEGRepresentation(self.choose3Image, NORMALSIZE)];
    
    [[GCQiniuUploadManager sharedInstance] uploadDatas:dataarray progress:^(float percent) {
        
    } oneTaskCompletion:^(NSError *error, NSString *link, NSInteger index) {
        DYLog(@"upload index:%ld link:%@", index, link);
        if (link) {
            NSString *resurl = [NSString stringWithFormat:@"%@/%@", QNHOST, link];
            [self.imgurlArray addObject:resurl];
            [self.imgidArray addObject:link];
            
        }
        
    } allTasksCompletion:^{
        [WDData sharedWDData].imgArr = self.imgurlArray;
        [WDData sharedWDData].idArr = self.imgidArray;
        NSLog(@"9999999%ld,,,,,%ld",[WDData sharedWDData].imgArr.count,self.imgurlArray.count);
        
    }];
}

- (void)nextClick
{
    if (self.chooseImage == nil || self.choose2Image == nil ||self.choose3Image == nil) {
        [ViewFactory showInfoMsg:@"请添加完整信息！"];
        return;
    }
    
    IdentityThirdViewController *nextVC = [[IdentityThirdViewController alloc]init];
    [self.navigationController pushViewController:nextVC animated:YES];
    //    if (_codeField.text == _codeStr)
    //    {
    //        NextChangePhoneViewController *next = [[NextChangePhoneViewController alloc]init];
    //        [self.navigationController pushViewController:next animated:YES];
    //    }
    //    else
    //    {
    //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"验证失败" message:@"请输入正确验证码" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
    //        [alert show];
    //    }
}
- (void) addClick:(ZYButton*)sender
{
    UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction* takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera];
    }];
    
    UIAlertAction* choosePictureAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self choosePhoto];
    }];
    
    [alertVC addAction:cancleAction];
    [alertVC addAction:takePhotoAction];
    [alertVC addAction:choosePictureAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)openCamera {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = sourceType;
    
    [self presentViewController:picker animated:YES completion:^{
    }];
}

- (void)choosePhoto {
    NSInteger maxCount = 1;
        QBImagePickerController *imagePickerController = [QBImagePickerController new];
        imagePickerController.assetCollectionSubtypes =@[
                                                         @(PHAssetCollectionSubtypeSmartAlbumUserLibrary), //相机胶卷
                                                         @(PHAssetCollectionSubtypeAlbumMyPhotoStream), //我的照片流
                                                         @(PHAssetCollectionSubtypeSmartAlbumPanoramas), //全景图
                                                         @(PHAssetCollectionSubtypeSmartAlbumBursts), //连拍模式拍摄的照片
                                                         @(PHAssetCollectionSubtypeSmartAlbumFavorites)
                                                         ];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.mediaType = QBImagePickerMediaTypeImage;
        imagePickerController.maximumNumberOfSelection = maxCount;
        imagePickerController.showsNumberOfSelectedAssets = YES;
        [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    [picker dismissViewControllerAnimated:YES completion:^{
        if (self.type == 1) {
            self.chooseImage = image;
        } else if (self.type == 2) {
            self.choose2Image = image;
        } else if (self.type == 3) {
            self.choose3Image = image;
        }
        [self uploadImages];
        [_mainTableView reloadData];
        
    }];
}

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
    NSUInteger count = assets.count;
    __block NSUInteger select = 0;
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.synchronous = YES;
    for (PHAsset *asset in assets) {
        [[PHCachingImageManager defaultManager]requestImageDataForAsset:asset options:option resultHandler:^(NSData * imageData, NSString * dataUTI, UIImageOrientation orientation, NSDictionary * info) {
            if(imageData) {
                if (self.type == 1) {
                    self.chooseImage = [UIImage imageWithData:imageData];
                } else if (self.type == 2) {
                    self.choose2Image = [UIImage imageWithData:imageData];
                } else if (self.type == 3) {
                    self.choose3Image = [UIImage imageWithData:imageData];
                }
                select++;
            }
            if(select == count) {
                [imagePickerController dismissViewControllerAnimated:YES completion:NULL];
                [self uploadImages];
                [_mainTableView reloadData];
                return;
            }
        }];
        
    }
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    [imagePickerController dismissViewControllerAnimated:NO completion:NULL];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

ARRAY_INIT(imgidArray)
ARRAY_INIT(imgurlArray)

@end
